import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Animated,
    Image,
    PanResponder,
    DeviceEventEmitter
} from 'react-native';

import { ToastToUser } from '../../utils/CustomToast';
import AndroidModule from '../../utils/AndroidConnent';
import Loading from "../../utils/Loading";

const isIos = Platform.OS == 'ios';

const screenW = Dimensions.get('window').width;

let timeIntever = 200;

let second = 0;
let pressSec = 0;

let startPanY = 0; //刚开始滑动的y坐标
let bottomHeight = 175 

let isUploadAudio = false

export default class AudioRecordPage extends Component {

    constructor(props) {
        super(props);
        this.panResponder = {}
        this.state = {
            fadeAnim: new Animated.Value(0),
            bottomViewHeight: bottomHeight,
            bottomSpce: new Animated.Value(-bottomHeight),
            show: false,
            secondStr: 0,
            onPressSec: 0,
            recordAlpha: 1.0,
            showRecordState: false,//是否显示录音状态
            recordState: '0', //0:手指上滑，取消发送，1:松开手指，取消发送
            voiceVolume: 1, //音量大小
        }
        if (props.onRef) {
            props.onRef(this)
        }
    };

    fadeIn = () => {
        this.state.bottomSpce.setValue(-this.state.bottomViewHeight);
        Animated.timing(
            this.state.bottomSpce,
            {
                toValue: 0,
                duration: timeIntever,
            },
        ).start();

        Animated.timing(this.state.fadeAnim, {
            toValue: 0.4,
            duration: timeIntever
        }).start();
    };

    fadeOut = (finish) => {
        Animated.timing(
            this.state.bottomSpce,
            {
                toValue: -this.state.bottomViewHeight,
                duration: timeIntever,
            },
        ).start();

        Animated.timing(this.state.fadeAnim, {
            toValue: 0,
            duration: timeIntever
        }).start(() => {
            this.setState({
                show: false,
            })
        }
        );
    };

    render() {
        if (this.state.show) {
            return (
                <View style={styles.container}>
                    <TouchableOpacity style={styles.translucentBox} activeOpacity={1.0} onPress={this.closeActionSheet.bind(this)} >
                        <Animated.View style={[styles.translucentBox, { backgroundColor: 'rgba(0,0,0,1.0)', opacity: this.state.fadeAnim }]} />
                        {
                            this.state.showRecordState ?
                                <View style={styles.recordStateBg}>
                                    <View style={{flexDirection:'row', alignItems:'flex-end'}}>
                                        <Image style={styles.recordStateIcon} source={{ uri: this.state.recordState == '0' ? 'https://static.hx2car.com/resource/web/dist/static/mobile/app/images/audio_recording_icon@3x.png' : 'https://static.hx2car.com/resource/web/dist/static/mobile/app/images/audio_record_cancel_icon@3x.png' }} />
                                        {
                                            this.state.recordState == '0' ?
                                            <Image style={styles.voiceVolumeIcon} source={{uri: 'https://static.hx2car.com/resource/web/dist/static/mobile/app/images/voice_volume_'+this.state.voiceVolume+'@3x.png'}}/>
                                            :
                                            null
                                        }
                                    </View>
                                    <View style={[styles.recordStateTextBg, { backgroundColor: this.state.recordState == '0' ? 'rgba(0,0,0,0)' : '#864440' }]}>
                                        <Text style={styles.recordStateText}>{this.state.recordState == '0' ? '手指上滑，取消发送' : '松开手指，取消发送'}</Text>
                                    </View>
                                </View>
                                :
                                null
                        }
                    </TouchableOpacity>
                    <Animated.View style={[styles.confirmbox, { bottom: this.state.bottomSpce }]}>
                        <Text style={styles.timeText}>{this.state.secondStr}</Text>

                        <View {...this.panResponder.panHandlers} style={styles.recordBg}>
                            <View style={[styles.recordBox, { backgroundColor: 'rgba(255,102,0,' + this.state.recordAlpha + ')' }]}>
                                <Image style={styles.recordIcon} source={require('source/image/audio_record.png')} />
                            </View>
                            <Text style={styles.recordText}>按住说</Text>
                        </View>
                    </Animated.View>

                    <Loading onRef={ref => this.Loading = ref} loadingText={'正在发送中...'} />

                </View>
            );
        } else {
            return <View />
        }
        
        
    }

    voiceAnimationStart() {
        if (!this.volumetimer) {
            this.volumetimer = setInterval(() => {
                let count = this.state.voiceVolume;
                count++;
                if (count == 7) {
                    count = 1
                }
                this.setState({
                    voiceVolume: count
                })
            }, 400);
        }
    }

    voiceAnimationStop() {
        if (this.volumetimer) {
            clearInterval(this.volumetimer);
            this.volumetimer = null
        }
        this.setState({
            voiceVolume: 1
        })
    }

    show = () => {
        this.setState({
            show: true
        }, function () {
            this.fadeIn();
            this.getTime(second)
            if (!isIos) {
                try {
                    AndroidModule.checkAudioPermission((success) => {
                        console.log('checkAudioPermission', success)
                        if (success) {
                            console.log('initAudioConfig')
                            AndroidModule.initAudioConfig()
                        } else {

                            this.hide()
                        }
                    })
                } catch (e) {

                }
            }
        })
        if(this.props.audioRecordHasShow) {
            this.props.audioRecordHasShow()
        }
    };

    hide = () => {
        this.fadeOut();
        second = 0;
        pressSec = 0
        this.setState({
            showRecordState: false,
            recordState: '0',
        })

        this.voiceAnimationStop();

        if (this.pressTimer) {
            clearInterval(this.pressTimer);
        }

        if (this.timer) {
            clearInterval(this.timer);
        }
    };

    componentDidMount() {
        isUploadAudio = false

        this.uploadAudioFailedListener = DeviceEventEmitter.addListener('uploadAudioFailed', e => {

            this.hide()

        });

        this.uploadAudioFinishListener = DeviceEventEmitter.addListener('uploadAudioFinish', e => {

            if (this.Loading) {
                this.Loading.hide()
            }

            if (isUploadAudio) {
                isUploadAudio = false
                if (!isIos) {
                    this.setState({
                        show: false,
                    })
                }

                let obj = {
                    url: e.url,
                    second: second
                }
                this.props.audioRecordResult(obj)
            }

        });

        this.getTime(second);
    }

    componentWillUnmount() {
        isUploadAudio = false
        
        if (this.uploadAudioFinishListener) {
            this.uploadAudioFinishListener.remove();
        }
        if (this.uploadAudioFailedListener) {
            this.uploadAudioFailedListener.remove();
        }
        second = 0
        pressSec = 0
    }

    componentWillMount() {
        this.panResponder = PanResponder.create({
            onStartShouldSetPanResponderCapture: (evt, gestureState) => {
                // 在触摸事件 开始，RN父布局组件会回调 onStartShouldSetResponderCapture，询问是否要拦截事件，自己接收处理， true 表示拦截。
                return true;
            },
            onStartShouldSetPanResponder: (evt, gestureState) => {
                /**
                 * 在手指触摸开始时申请成为响应者
                 */
                // console.log('onStartShouldSetPanResponder')
                // console.log(gestureState)
                return true;
            },

            onPanResponderStart: (evt, gestureState) => {
                startPanY = evt.nativeEvent.pageY
                /**
                 * 表示手指按下时，成功申请为事件响应者的回调
                 */
                this.setState({
                    recordAlpha: 0.5,
                    showRecordState: true
                })

                pressSec = 0;
                this.pressTimer = setInterval(() => {
                    pressSec += 1;
                }, 90);

                this.voiceAnimationStart();

                setTimeout(() => {
                    if (pressSec >= 1) {
                        this.startRecord();
                    }
                }, 100);
            },

            onPanResponderMove: (evt, gestureState) => {
                if (startPanY - evt.nativeEvent.pageY > 50) {//向上滑动50
                    this.setState({
                        recordState: '1'
                    })
                } else {
                    this.setState({
                        recordState: '0'
                    })
                }
            },

            onPanResponderTerminate: (evt, gestureState) => {
                this.setState({
                    recordAlpha: 1.0,
                    showRecordState: false
                }, function () {
                    this.stopRecord();
                    setTimeout(() => {
                        this.closeActionSheet()
                    }, 250);

                })
            },

            onPanResponderRelease: (evt, gestureState) => {
                console.log('onPanResponderRelease')
                //用户放开了所有的触摸点，且此时视图已经成为了响应者。
                //一般来说这个意味着一个手势操作已经完成了。
                /**
                 * 表示触摸完成(touchUp)的时候的回调，表示用户完成了本次的触摸交互，这里应该完成手势识别的处理，
                 * 这以后，组件不再是事件响应者，组件取消激活
                 */

                if (this.state.recordState == '0') {//录制完成
                    if (pressSec >= 1) {//有录制结果
                        pressSec = 0;
                        this.setState({
                            recordAlpha: 1.0,
                            showRecordState: false
                        }, function () {
                            if (this.pressTimer) {
                                clearInterval(this.pressTimer);
                            }
                            this.stopRecord();
                            setTimeout(() => {
                                this.uploadRecord()
                            }, 1000);
                        })
                    } else {//录制时间太短
                        ToastToUser('按住时间太短');
                        pressSec = 0;
                        this.setState({
                            recordAlpha: 1.0,
                            showRecordState: false
                        }, function () {
                            if (this.pressTimer) {
                                clearInterval(this.pressTimer);
                            }
                            if (this.timer) {
                                clearInterval(this.timer);
                            }
                        })
                    }
                } else if (this.state.recordState == '1') {//取消录制
                    this.setState({
                        recordAlpha: 1.0,
                        showRecordState: false
                    }, function () {
                        this.stopRecord();
                        this.againRecord()
                        setTimeout(() => {
                            this.closeActionSheet()
                        }, 250);
                    })
                }

                return true;
            },

        });
    }

    startRecord() {
        this.timer = setInterval(() => {
            second += 1;
            this.getTime(second)
        }, 1000);

        try {
            AndroidModule.startAudioRecord();
        } catch (error) {

        }
    }

    stopRecord() {
        if (this.timer) {
            clearInterval(this.timer);
        }

        try {
            AndroidModule.stopAudioRecord();
        } catch (error) {

        }
    }

    againRecord() {
        second = 0;
        this.getTime(second);

        try {
            AndroidModule.stopAudio();
        } catch (error) {

        }
    }

    uploadRecord() {
        try {
            isUploadAudio = true
            if (isIos) {
                AndroidModule.uploadAudio();
            } else {
                this.Loading.show()
                setTimeout(() => {
                    AndroidModule.uploadAudio();
                }, 2000)
            }

        } catch (error) {

        }
    }

    stopAudio() {
        try {
            AndroidModule.stopAudio();
        } catch (error) {

        }
    }

    palyAudio() {
        try {
            AndroidModule.palyLocalAudio();
        } catch (error) {

        }
    }

    getTime(data) {
        let hour = Math.floor((data / 3600) % 24);
        let minute = Math.floor((data / 60) % 60);
        let second = Math.floor(data % 60);
        let strend = ''
        strend = hour < 10 ? "0" + hour : hour,
            strend += ":",
            strend += minute < 10 ? "0" + minute : minute,
            strend += ":",
            strend += second < 10 ? "0" + second : second + ''
        this.setState({
            secondStr: strend,
        })
    }

    sureAction(index) {
        if (this.props.sureHandler) {
            this.props.sureHandler(index);
        }
        this.hide();
    }

    closeActionSheet = () => {
        second = 0;
        this.getTime(second);
        this.hide();
    }

    cancelAction() {
        this.hide();
    }

}


const styles = StyleSheet.create({
    container: {
        position: "absolute",
        left: 0,
        top: 0,
        bottom: 0,
        right: 0,
        justifyContent: "center",
        alignItems: "center",
        zIndex: 1000,
    },
    translucentBox: {
        position: 'absolute',
        width: '100%',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center'
    },
    recordStateBg: {
        width: 144,
        height: 144,
        borderRadius: 4,
        backgroundColor: 'rgba(0,0,0,0.5)',
        justifyContent: 'center',
        alignItems: 'center'
    },
    voiceVolumeIcon:{
        width: 28,
        height: 53,
        marginBottom:5,
    },
    recordStateIcon: {
        width: 87,
        height: 87,
    },
    recordStateTextBg: {
        marginTop: 5,
        paddingHorizontal: 5,
        paddingVertical: 3,
        borderRadius: 3
    },
    recordStateText: {
        color: '#ffffff',
        fontSize: 13,
    },
    confirmbox: {
        width: screenW,
        height: bottomHeight,
        backgroundColor: '#FFFFFF',
        position: 'absolute',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'flex-start',
        paddingTop: 24,
    },
    timeText: {
        fontSize: 15,
        color: '#666666',
        marginBottom: 8,
    },
    recordBg: {
        flexDirection: 'column',
        alignItems: 'center',
    },
    recordBox: {
        width: 80,
        height: 80,
        borderRadius: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(255,102,0,1)'
    },
    recordIcon: {
        width: 37,
        height: 37
    },
    recordText: {
        color: '#999999',
        fontSize: 12,
        marginTop: 8,
    },
    playIcon: {
        width: 64,
        height: 64
    },
    bottomBox: {
        marginTop: 17,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: screenW - 80
    },
    bottomItemBox: {
        width: 60,
        height: 28,
        borderRadius: 14,
        borderColor: '#999999',
        borderWidth: 0.5,
        justifyContent: 'center',
        alignItems: 'center'
    },
    itemText: {
        color: '#999999',
        fontSize: 12
    },

});